package org.hpin.xyxyFile.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.hpin.base.usermanager.entity.User;
import org.hpin.common.core.SpringTool;
import org.hpin.common.core.web.BaseAction;
import org.hpin.common.util.HttpTool;
import org.hpin.common.util.StrUtils;
import org.hpin.common.widget.pagination.Page;
import org.hpin.xyxyFile.entity.XyxyFm;
import org.hpin.xyxyFile.service.XyxyFmService;

@Namespace("/xyxyFile")
@Action("xyxyFmAction")
@Results({
	@Result(name="listXyxyFm" ,location = "/WEB-INF/xyxyFile/listXyxyFm.jsp"),
	@Result(name="addXyxyFm" ,location = "/WEB-INF/xyxyFile/addXyxyFm.jsp"),
	@Result(name="browXyxyFm" ,location = "/WEB-INF/xyxyFile/browXyxyFm.jsp"),
	@Result(name="modifyXyxyFm", location = "/WEB-INF/xyxyFile/modifyXyxyFm.jsp"),
	})
public class XyxyFmAction extends BaseAction{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -666419615426406028L;
	private XyxyFm xyxyFm;
	private XyxyFmService xyxyFmService = (XyxyFmService)SpringTool.getBean(XyxyFmService.class);
	
	private  File file;
    private  String fileFileName;  //上传的文件名
    
	public String listXyxyFm() throws Exception{
		page = new Page(HttpTool.getPageNum(),HttpTool.getPageSize());
		Map searchMap = super.buildSearch();
		findByPage(page, searchMap);
		return "listXyxyFm";
	}
	public Page findByPage(Page page , Map searchMap){
		xyxyFmService.findByPage(page, searchMap);
		return page ;
	}
	
	public String addXyxyFm(){
		HttpTool.setAttribute("navTabId", HttpTool.getParameter("navTabId"));
		
		if(StrUtils.isNotNullOrBlank(id)){
			xyxyFm=(XyxyFm) xyxyFmService.findById(id);
			HttpTool.setAttribute("id", id);
		}else{
			xyxyFm = new XyxyFm();
		}
		return "addXyxyFm";
	}
	
	//增加保存到数据库
	public String saveXyxyFm(){
		JSONObject json = new JSONObject();
		try {
			User currentUser = (User)HttpTool.getSession().getAttribute("currentUser");
			String path=HttpTool.getSession().getServletContext().getRealPath("/WEB-INF/upload");//得到要保存上传文件的目录的绝对路径。
			File target= new File(path, fileFileName);
			FileUtils.copyFile(file, target);
			String savePath=path;//获取文件路径
			
			xyxyFm.setfName(fileFileName);
			xyxyFm.setPath(savePath);
			xyxyFm.setCreateTime(new Date());
			xyxyFm.setTeaName(currentUser.getUserName());
			xyxyFm.setIsDeleted(0);
			xyxyFmService.save(xyxyFm);
			json.accumulate("statusCode", 200);
			json.accumulate("message", "操作成功");
			json.accumulate("navTabId", super.navTabId);
			json.accumulate("callbackType", "closeCurrent");
		} catch (Exception e) {
			json.accumulate("statusCode", 300);
			json.accumulate("message", "操作失败");
			e.printStackTrace();
		}
		renderJson(json);
		return null;
	}
	
	/**
	 * 删除
	 * @return
	 * @throws IOException
	 * @author Marver
	 */
	public String deleteXyxyFm() throws IOException{
		JSONObject json = new JSONObject();
		try {
			String[] id = ids.replaceAll(" ", "").split(",");
			for(int i=0;i<id.length;i++){
				xyxyFm=(XyxyFm) xyxyFmService.findById(id[i]);
				String downName=xyxyFm.getRemark();
				String savepath = xyxyFm.getPath()+"\\"+downName;
				File f = new File(savepath);
				f.delete();
			}
			xyxyFmService.deleteMSG(id);
			json.accumulate("statusCode", 200);
			json.accumulate("message", "操作成功");
			json.accumulate("navTabId", super.navTabId);
			json.accumulate("callbackType", "");
			json.accumulate("forwardUrl", "");
			json.accumulate("confirmMsg", "");
		} catch (Exception e) {
			json.accumulate("statusCode", 300);
			json.accumulate("message", "操作失败");
			e.printStackTrace();
		}
		renderJson(json);
		return null;
	}
	//修改前查询
	public String modifyXyxyFm(){
		xyxyFm=(XyxyFm) xyxyFmService.findById(id);
		return "modifyXyxyFm";
	}
	//修改信息
	public String updateXyxyFm() throws IOException, IllegalAccessException, InvocationTargetException {
		JSONObject json = new JSONObject();
		try {
			User currentUser = (User)HttpTool.getSession().getAttribute("currentUser");
			xyxyFm.setUpName(currentUser.getUserName());
			xyxyFmService.update(xyxyFm);
			json.accumulate("statusCode", 200);
			json.accumulate("message", "操作成功");
			json.accumulate("navTabId", super.navTabId);
			json.accumulate("callbackType", "closeCurrent");
		} catch (Exception e) {
			json.accumulate("statusCode", 300);
			json.accumulate("message", "操作失败");
			e.printStackTrace();
		}
		renderJson(json);
		
		return null;
	}
	//**查询详细信息
	public String browXyxyFm(){
		xyxyFm=(XyxyFm) xyxyFmService.findById(id);
		return "browXyxyFm";
	}
	
	//附件下载
		public String downXyxyFm() throws IOException{
			JSONObject json = new JSONObject();
			xyxyFm=(XyxyFm) xyxyFmService.findById(id);
			if(xyxyFm==null){
				json.accumulate("statusCode", 300);
				json.accumulate("message", "资源已被删除");
				renderJson(json);
			}
			FileInputStream in=null;
			OutputStream out=null;
			try {
				String downName=xyxyFm.getfName();
				String savepath = xyxyFm.getPath()+"\\"+downName;
				
				File f = new File(savepath);
				System.out.println(savepath);
				
			
				HttpTool.getResponse().setHeader("content-disposition",
						"attachment;filename="+transCharacter(HttpTool.getRequest(),downName));
				in = new FileInputStream(f);
				out = HttpTool.getResponse().getOutputStream();
				byte[] buf = new byte[1024];
				int len = 0;
				while((len=in.read(buf))>0){
					out.write(buf, 0, len);
				}
			}catch(Exception e){
				json.accumulate("statusCode", 300);
				json.accumulate("message", "未找到该资源");

				renderJson(json);
				e.printStackTrace();
			}finally{
				in.close();
				out.close();
			}
			
			return null;
		}
	
	
	public XyxyFm getXyxyFm() {
			return xyxyFm;
		}
		public void setXyxyFm(XyxyFm xyxyFm) {
			this.xyxyFm = xyxyFm;
		}
		public XyxyFmService getXyxyFmService() {
			return xyxyFmService;
		}
		public void setXyxyFmService(XyxyFmService xyxyFmService) {
			this.xyxyFmService = xyxyFmService;
		}
	public File getFile() {
		return file;
	}
	public void setFile(File file) {
		this.file = file;
	}
	public String getFileFileName() {
		return fileFileName;
	}
	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}
	
	/** 
	 * 根据不同的浏览器转字符编码 
	 * @param request 
	 * @param str 
	 * @return 
	 * @throws Exception 
	 */  
	private String transCharacter(HttpServletRequest request, String str) throws Exception{  
	    if(request.getHeader("USER-AGENT").toLowerCase().indexOf( "msie" ) > 0){  
	        return URLEncoder.encode(str, "UTF-8");  
	    }else if(request.getHeader("USER-AGENT").toLowerCase().indexOf( "firefox" ) > 0){  
	        return new String(str.getBytes("UTF-8"), "ISO8859-1");  
	    }  
	    return new String(str.getBytes("UTF-8"), "ISO8859-1");  
	}  
	
	
}
